package com.mti.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mti.component.UserTypeInfo;
import com.mti.component.redis.RedisUtil;
import com.mti.configuration.SystemConfig;
import com.mti.constant.AlarmFilterEnum;
import com.mti.constant.ZdryYjLx;
import com.mti.dao.dto.OrganizationDto;
import com.mti.dao.kmmodel.KmArmingTaskEntity;
import com.mti.dao.kmmodel.KmArmingTaskJsonEntity;
import com.mti.dao.model.*;
import com.mti.dao.qo.KmAlarmAreaQO;
import com.mti.dao.qo.KmAlarmFilterQo;
import com.mti.dao.qo.LfRyyjsjQO;
import com.mti.dao.qo.YjInfoParamQo;
import com.mti.dao.vo.ZdryTxVo;
import com.mti.dao.vo.ZdryYjPushDataVo;
import com.mti.dao.vo.ZdryYjPushToDsUtil;
import com.mti.dao.vo.ZdryYjStatisticsVo;
import com.mti.enums.RoleType;
import com.mti.exception.BusinessException;
import com.mti.jwt.AccountBo;
import com.mti.jwt.RequestUtils;
import com.mti.mapper.LfZtryyjMapper;
import com.mti.service.*;
import com.mti.utils.DateUtils;
import com.mti.utils.ExeclUtil;
import com.mti.utils.JsonFileParseUtil;
import com.mti.utils.ZdryQxzkUtilBean;
import io.jsonwebtoken.lang.Collections;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor
public class LfZtryyjsjServiceImpl extends ServiceImpl<LfZtryyjMapper, LfZtryyjEntity> implements ILfZtryyjsjService {
    @Autowired
    private TKmGlkygpService tKmGlkygpService;
    @Autowired
    private TKmLgzsService tKmLgzsService;
    @Autowired
    private TKmMhdzService tKmMhdzService;
    @Autowired
    private TKmMhlgService tKmMhlgService;
    @Autowired
    private TKmTldpv2Service tKmTldpv2Service;
    @Autowired
    private TKmWbswService tKmWbswService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ISysDictService iSysDictService;
    @Autowired
    private KmZdryTypeService kmZdryTypeService;
    @Autowired
    private CacheableService cacheableService;
    @Autowired
    private RequestUtils requestUtils;
    @Autowired
    private KmPhYjService kmPhYjService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private KmRlsbService kmRlsbService;
    @Autowired
    private IKmArmingTaskService taskService;
    @Autowired
    private TSwitchTypeServie tSwitchTypeServie;
    @Autowired
    private KmAlarmAreaService kmAlarmAreaService;
    @Autowired
    private KmAlarmTypeService kmAlarmTypeService;
    @Autowired
    private LfZdryBaseService lfZdryBaseService;

    private static final int LIST_SIZE = 10000;

    private static final List<String> ssxqes = Arrays.asList("530113000000", "530129000000", "530127000000", "530125000000",
            "530126000000", "530128000000", "530124000000", "530181000000", "530122000000");

    private static final Map<String, String> yjdFjNameMap = new HashMap<String, String>() {
        {
            put("东川分局", "530113000000");
            put("东川区公安局", "530113000000");
            put("寻甸县局", "530129000000");
            put("寻甸回族彝族自治县公安局", "530129000000");
            put("嵩明县局", "530127000000");
            put("嵩明县公安局", "530127000000");
            put("宜良县局", "530125000000");
            put("宜良县公安局", "530125000000");
            put("石林县局", "530126000000");
            put("石林彝族自治县公安局", "530126000000");
            put("禄劝县局", "530128000000");
            put("禄劝彝族苗族自治县公安局", "530128000000");
            put("富民县局", "530124000000");
            put("富民县公安局", "530124000000");
            put("安宁市局", "530181000000");
            put("安宁市公安局", "530181000000");
            put("晋宁分局", "530122000000");
        }
    };

    @Override
    public IPage<LfZtryyjEntity> getZdryYjInfo(LfRyyjsjQO qo, ServerWebExchange exchange) {
        Page<LfZdryEntity> page = new Page<>(qo.getStart(), qo.getSize());
        // 验证账户权限
        setUpAuthority(exchange, qo);
        //如果存在布控任务（布控任务Id不为空）
        if (!StringUtils.isEmpty(qo.getBkrwId())) {
            IPage<LfZtryyjEntity> iPage = getLfZtryyjEntityIPage(qo);
            if (iPage != null) {
                return iPage;
            }
        } else {
            alarmFilter(qo);
        }

        return this.getBaseMapper().getZdryYjXx(page, qo);
    }


    @Override
    public List<LfZtryyjEntity> queryAlarmFilterData(KmAlarmFilterQo qo) {
        //满足上方布控区域内开启状态下的”手机预警”，“人脸识别“
        alarmFilterForQuery(qo);
        return this.getBaseMapper().queryAlarmFilterData(qo);
    }

    @Override
    public void updateAlarmFilterMark(List<String> list) {
        this.getBaseMapper().updateAlarmFilterMark(list);
    }

    @Override
    public boolean authEarlyWarning(LfZtryyjEntity lfZtryyjEntity, String name) {
        //预警开关是否打开 true 打开  false 关闭
        KmAlarmTypeEntity kmAlarmTypeEntity = kmAlarmTypeService.getAlarmStatusByName(name);
        if (kmAlarmTypeEntity.isStatus()) {
            //预警是否在区域内部 true 在区域内 false 不在区域内
            KmAlarmAreaQO qo = new KmAlarmAreaQO();
            qo.setX(lfZtryyjEntity.getX());
            qo.setY(lfZtryyjEntity.getY());
            boolean inArea = kmAlarmAreaService.authIsInArea(qo);
            if (!inArea) {
                return false;
            }
        } else {
            return false;
        }

        //查询此条预警是否是灰名单 或者是 已稳控  如果是就不推送
        LfZdryBaseEntity entity = lfZdryBaseService.getOne(new QueryWrapper<LfZdryBaseEntity>().eq("sfzh", lfZtryyjEntity.getYjbs()).ne("gkjb", "灰名单").ne("wkzt", "已稳控"));
        if (!ObjectUtils.isEmpty(entity)) {
            return false;
        }
        return true;
    }

    /**
     * @return void
     * @Author hf
     * @Title: alarmFilterForQuery
     * @Description: TODO (预警处置规则条件设置)
     * @Param [qo]
     * @Date 2020/11/25 14:50
     */
    private void alarmFilterForQuery(KmAlarmFilterQo qo) {
        if (Collections.isEmpty(qo.getYjlxList())) {
            qo.setYjlxList(new ArrayList<>(Arrays.asList("tldp", "glky-gp", "lgzs", "mhdz", "wbsw", "mhlg", "phyj", "rlsb")));
        }
        //加入成功后，进行数据过滤和判断
        KmAlarmTypeEntity phyj = kmAlarmTypeService.getAlarmStatusByName(AlarmFilterEnum.PHONE_SWITCH.getName());
        List list = new ArrayList();
        //手机预警开关是否打开
        if (phyj.isStatus() && qo.getYjlxList().contains(AlarmFilterEnum.PHONE_SWITCH.getKey())) {
            list.add(AlarmFilterEnum.PHONE_SWITCH.getKey());
            qo.getYjlxList().remove(AlarmFilterEnum.PHONE_SWITCH.getKey());
        }

        //加入成功后，进行数据过滤和判断
        KmAlarmTypeEntity rlsb = kmAlarmTypeService.getAlarmStatusByName(AlarmFilterEnum.RLSB_SWITCH.getName());
        //人脸识别开关是否打开
        if (rlsb.isStatus() && qo.getYjlxList().contains(AlarmFilterEnum.RLSB_SWITCH.getKey())) {
            list.add(AlarmFilterEnum.RLSB_SWITCH.getKey());
            qo.getYjlxList().remove(AlarmFilterEnum.RLSB_SWITCH.getKey());
        }
        if (phyj.isStatus() || rlsb.isStatus()) {
            qo.setSubYjlxList(list);
            qo.setGisModels(kmAlarmAreaService.getAreaList());
        }

    }

    /**
     * @return void
     * @Author hf
     * @Title: alarmFilter
     * @Description: TODO (预警筛选条件,预警查询表)
     * @Param [qo]
     * @Date 2020/11/24 15:53
     */
    private void alarmFilter(LfRyyjsjQO qo) {
        //如果是空的话，默认是查询全部类型
        if (Collections.isEmpty(qo.getYjlbxs())) {
            qo.setYjlbxs(new ArrayList<>(Arrays.asList("tldp", "glky-gp", "lgzs", "mhdz", "wbsw", "mhlg", "phyj", "rlsb")));
        }
        if (StringUtils.isEmpty(qo.getBkrwId())) {
            //普通预警查询
            //加入成功后，进行数据过滤和判断
            KmAlarmTypeEntity phyj = kmAlarmTypeService.getAlarmStatusByName(AlarmFilterEnum.PHONE_SWITCH.getName());
            List list = new ArrayList();
            //手机预警开关是否打开
            if (phyj.isStatus() && qo.getYjlbxs().contains(AlarmFilterEnum.PHONE_SWITCH.getKey())) {
                list.add(AlarmFilterEnum.PHONE_SWITCH.getKey());
                qo.getYjlbxs().remove(AlarmFilterEnum.PHONE_SWITCH.getKey());
            }
            //加入成功后，进行数据过滤和判断
            KmAlarmTypeEntity rlsb = kmAlarmTypeService.getAlarmStatusByName(AlarmFilterEnum.RLSB_SWITCH.getName());
            //人脸识别开关是否打开
            if (rlsb.isStatus() && qo.getYjlbxs().contains(AlarmFilterEnum.RLSB_SWITCH.getKey())) {
                list.add(AlarmFilterEnum.RLSB_SWITCH.getKey());
                qo.getYjlbxs().remove(AlarmFilterEnum.RLSB_SWITCH.getKey());
            }

            if (phyj.isStatus() || rlsb.isStatus()) {
                qo.setYjlxList(list);
                qo.setGisModels(kmAlarmAreaService.getAreaList());
            }
        }


    }

    /**
     * 布控任务逻辑单独封装
     *
     * @param qo
     * @return
     */
    private IPage<LfZtryyjEntity> getLfZtryyjEntityIPage(LfRyyjsjQO qo) {
        KmArmingTaskEntity taskEntity = taskService.getById(qo.getBkrwId());
        List<String> personIdList = new ArrayList<>();
        if (taskEntity != null) {
            if (!org.springframework.util.StringUtils.isEmpty(taskEntity.getArmingRange())) {
                qo.setGisModels(taskService.getGisModels(taskEntity.getArmingRange()));
            }
            if (!org.springframework.util.StringUtils.isEmpty(taskEntity.getArmingValue())) {
                KmArmingTaskJsonEntity jsonEntity = JSONObject.parseObject(taskEntity.getArmingValue(), KmArmingTaskJsonEntity.class);
                List<String> personListJson = jsonEntity.getPersonList();
                personListJson.parallelStream().forEach(item -> {
                    JSONObject personMessage = JSONObject.parseObject(item);
                    String personId = personMessage.getString("id");
                    personIdList.add(personId);
                });
                List<String> yjlxList = jsonEntity.getControlTypeList().parallelStream().map(item -> JSONObject.parseObject(item).getString("name")).collect(Collectors.toList());
                if (yjlxList != null && !yjlxList.isEmpty()) {
                    //布控任务只针对手机预警和人脸识别 可以在布控任务数据中再进行二次筛选
                    if (!yjlxList.containsAll(qo.getYjlbxs()) || Collections.isEmpty(qo.getYjlbxs())) {
                        qo.setYjlbxs(yjlxList);
                    }
                }
                qo.setPersonIdList(personIdList);
                qo.setRylbxList(jsonEntity.getRylbxList());
                qo.setZrbmList(jsonEntity.getZrbmList());
                qo.setWkztList(jsonEntity.getWkztList());
                qo.setRysxList(jsonEntity.getRysxList());

                if (jsonEntity.getQueryList() != null && !jsonEntity.getQueryList().isEmpty() && qo.getZrfj() != null && !qo.getZrfj().isEmpty()) {
                    Set<String> zrfjSet = new HashSet<>(jsonEntity.getQueryList());
                    List<String> list = new ArrayList<>();
                    for (String s : qo.getZrfj()) {
                        if (!zrfjSet.add(s)) {
                            list.add(s);
                        }
                    }
                    if (list.isEmpty()) {
                        list.add("##");
                    }
                    qo.setZrfj(list);
                } else if (jsonEntity.getQueryList() != null && !jsonEntity.getQueryList().isEmpty() && (qo.getZrfj() == null || qo.getZrfj().isEmpty())) {
                    qo.setZrfj(jsonEntity.getQueryList());
                }
                //管控级别
                if (jsonEntity.getGkjbxList() != null && !jsonEntity.getGkjbxList().isEmpty() && qo.getGkjbxList() != null && !qo.getGkjbxList().isEmpty()) {
                    Set<String> gkjbSet = new HashSet<>(jsonEntity.getGkjbxList());
                    List<String> list = new ArrayList<>();
                    for (String s : qo.getGkjbxList()) {
                        if (!gkjbSet.add(s)) {
                            list.add(s);
                        }
                    }
                    if (list.isEmpty()) {
                        list.add("##");
                    }
                    qo.setGkjbxList(list);
                } else if (jsonEntity.getGkjbxList() != null && !jsonEntity.getGkjbxList().isEmpty() && (qo.getGkjbxList() == null || qo.getGkjbxList().isEmpty())) {
                    qo.setGkjbxList(jsonEntity.getGkjbxList());
                }

                //预警处置类别
                if (jsonEntity.getYjczlbList() != null && !jsonEntity.getYjczlbList().isEmpty() && qo.getYjczlbList() != null && !qo.getYjczlbList().isEmpty()) {
                    Set<String> yjczSet = new HashSet<>(jsonEntity.getYjczlbList());
                    List<String> list = new ArrayList<>();
                    for (String s : qo.getYjczlbList()) {
                        if (!yjczSet.add(s)) {
                            list.add(s);
                        }
                    }
                    if (list.isEmpty()) {
                        list.add("##");
                    }
                    qo.setYjczlbList(list);
                } else if (jsonEntity.getYjczlbList() != null && !jsonEntity.getYjczlbList().isEmpty() && (qo.getYjczlbList() == null || qo.getYjczlbList().isEmpty())) {
                    qo.setYjczlbList(jsonEntity.getYjczlbList());
                }

                if (jsonEntity.getYnzsList() != null && !jsonEntity.getYnzsList().isEmpty() && qo.getYnzsList() != null && !qo.getYnzsList().isEmpty()) {
                    Set<String> ynzsListSet = new HashSet<>(jsonEntity.getYnzsList());
                    List<String> list = new ArrayList<>();
                    for (String s : qo.getYnzsList()) {
                        if (!ynzsListSet.add(s)) {
                            list.add(s);
                        }
                    }
                    if (list.isEmpty()) {
                        list.add("##");
                    }
                    qo.setYnzsList(list);
                } else if (null != jsonEntity.getYnzsList() && !jsonEntity.getYnzsList().isEmpty() && (null == qo.getYnzsList() || qo.getYnzsList().isEmpty())) {
                    qo.setYnzsList(jsonEntity.getYnzsList());
                }

                boolean setSuccess = taskService.setTimeFlows(taskEntity.getId(), qo);
                if (!setSuccess) {
                    IPage<LfZtryyjEntity> iPage = new Page<>();
                    iPage.setTotal(0);
                    iPage.setRecords(new ArrayList<>());
                    return iPage;
                }
            }
        }
        return null;
    }

    @Override
    public IPage<LfZtryyjEntity> getYjTimeOutInfo(LfRyyjsjQO qo, ServerWebExchange exchange) {
        Page<LfZdryEntity> page = new Page<>(qo.getStart(), qo.getSize());
        setUpAuthority(exchange, qo);
        IPage<LfZtryyjEntity> ztryyjEntityIPage = this.getBaseMapper().getYjTimeOutInfo(page, qo);
        return ztryyjEntityIPage;
    }

    @Override
    public IPage<Map<String, Object>> getZdryAllYj(String sfzh, Integer offset, Integer pageSize) {
        Page<Map<String, Object>> page = new Page<>(offset, pageSize);
        IPage<Map<String, Object>> result = this.getBaseMapper().getZdryAllYjBySfzh(page, sfzh);
        return result;
    }

    @Override
    public List<Map<String, Object>> getZdryAllYjNoPage(String sfzh, String startTime, String endTime) {
        if (!"".equals(startTime) && !"".equals(endTime)) {
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 23:59:59";
        }
        //查询除手机定位外其他类型的预警数据
        List<Map<String, Object>> result = this.getBaseMapper().getZdryAllYjNoPage(sfzh, null, startTime, endTime);
        //手机定位预警数据(一个月)
        List<Map<String, Object>> resultPhone = this.getBaseMapper().getZdryAllYjNoPage(sfzh, "", startTime, endTime);
        List<Map<String, Object>> mapList = new ArrayList<>();
        //号码相同经纬度的手机定位数据，一小时内只取一条
        if (resultPhone.size() > 0) {
            mapList.add(resultPhone.get(0));
            for (int i = 0; i < resultPhone.size(); i++) {
                for (int j = i + 1; j < resultPhone.size(); j++) {
                    if (null != resultPhone.get(i).get("sjbs") && null != resultPhone.get(i).get("x") && null != resultPhone.get(i).get("y")) {
                        if (resultPhone.get(i).get("sjbs").equals(resultPhone.get(j).get("sjbs")) && resultPhone.get(i).get("x").equals(resultPhone.get(j).get("x")) && resultPhone.get(i).get("y").equals(resultPhone.get(j).get("y"))) {
                            String yjsjI = (String) resultPhone.get(i).get("yjsj");
                            String substringyjsjI = yjsjI.substring(0, 13);
                            String yjsjJ = (String) resultPhone.get(j).get("yjsj");
                            String substringyjsjJ = yjsjJ.substring(0, 13);
                            if (substringyjsjI.equals(substringyjsjJ)) {
                                mapList.add(resultPhone.get(i));
                            } else {
                                mapList.add(resultPhone.get(j));
                            }
                        } else {
                            mapList.add(resultPhone.get(j));
                        }
                    }
                }
            }
            List<Map<String, Object>> single = getSingle(mapList);
            result.addAll(single);
        }
        return result;
    }

    public ArrayList getSingle(List<Map<String, Object>> list) {
        ArrayList newList = new ArrayList();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Object obj = it.next();
            if (!newList.contains(obj)) {
                newList.add(obj);
            }
        }
        return newList;
    }

    @Override
    public Object getZdryTxzk(LfRyyjsjQO lfRyyjsjQO, ServerWebExchange exchange) {
        setUpAuthority(exchange, lfRyyjsjQO);
        Map<String, List<ZdryQxzkUtilBean>> resultMap = new HashMap<>();
        resultMap.put("mhOut", new ArrayList<>());
        resultMap.put("mhIn", new ArrayList<>());
        resultMap.put("tlOut", new ArrayList<>());
        resultMap.put("tlIn", new ArrayList<>());
        resultMap.put("kyOut", new ArrayList<>());
        resultMap.put("kyIn", new ArrayList<>());
        List<ZdryQxzkUtilBean> orData = this.getBaseMapper().getZdryTxzk(lfRyyjsjQO);
        for (ZdryQxzkUtilBean z : orData) {
            if (z.getYjlx() != null) {
                switch (z.getYjlx()) {
                    case "tldp": {
                        if (z.getInOut().intValue() == 1)
                            resultMap.get("tlIn").add(z);
                        else if (z.getInOut().intValue() == 2)
                            resultMap.get("tlOut").add(z);
                    }
                    break;
                    case "mhlg": {
                        if (z.getInOut().intValue() == 1)
                            resultMap.get("mhIn").add(z);
                        else if (z.getInOut().intValue() == 2)
                            resultMap.get("mhOut").add(z);
                    }
                    break;
                    case "mhdz": {
                        if (z.getInOut().intValue() == 1)
                            resultMap.get("mhIn").add(z);
                        else if (z.getInOut().intValue() == 2)
                            resultMap.get("mhOut").add(z);
                    }
                    break;
                    case "glky-gp": {
                        if (z.getInOut().intValue() == 1)
                            resultMap.get("kyIn").add(z);
                        else if (z.getInOut().intValue() == 2)
                            resultMap.get("kyOut").add(z);
                    }
                    break;
                }
            }
        }
        return resultMap;
    }

    @Override
    public Object queryWbLgKyNumber(LfRyyjsjQO lfRyyjsjQO, ServerWebExchange exchange) {
        Map<String, Object> resultMap = new HashMap<>();
        // 查询网吧信息
        List<Map<String, Object>> wbsw = new ArrayList<>();
        List<Map<String, Object>> lgzs = new ArrayList<>();
        List<Map<String, Object>> phyj = new ArrayList<>();
        List<Map<String, Object>> rlsb = new ArrayList<>();
        setUpAuthority(exchange, lfRyyjsjQO);
        List<Map<String, Object>> list = this.getBaseMapper().queryWbLgKyNumber(lfRyyjsjQO);
        list.forEach(e -> {
            if (e.containsKey("yjlx") && e.get("yjlx") != null) {
                if (e.get("yjlx").toString().equals("wbsw")) {
                    wbsw.add(e);
                } else if (e.get("yjlx").toString().equals("lgzs")) {
                    lgzs.add(e);
                } else if (e.get("yjlx").toString().equals("phyj")) {
                    phyj.add(e);
                } else if (e.get("yjlx").toString().equals("rlsb")) {
                    rlsb.add(e);
                }
            }
        });
        resultMap.put("wbsw", wbsw);
        resultMap.put("lgzs", lgzs);
        resultMap.put("phyj", phyj);
        resultMap.put("rlsb", rlsb);
        return resultMap;
    }

    /**
     * 根据筛选条件查询满足添加的省份证号
     *
     * @param lfRyyjsjQO
     * @return
     */
    private List<String> getSfzhByCondition(LfRyyjsjQO lfRyyjsjQO) {
        List<String> sfzhs = this.getBaseMapper().getSfzhByCondition(lfRyyjsjQO);
        return sfzhs;
    }

    @Override
    public Mono<DataBuffer> exportYjXx(LfRyyjsjQO lfRyyjsjQO, String exportName, ServerWebExchange exchange) throws Exception {
        DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory().allocateBuffer();
        OutputStream outputStream = dataBuffer.asOutputStream();
        // 每次写100行数据，就刷新数据出缓存
        SXSSFWorkbook wb = new SXSSFWorkbook(100);
        try {
            CellStyle cellStyleCenter = wb.createCellStyle();
            CellStyle cellStyleLeft = wb.createCellStyle();
            cellStyleCenter.setAlignment(HorizontalAlignment.CENTER); // 居中
            cellStyleCenter.setVerticalAlignment(VerticalAlignment.CENTER); // 居中
            cellStyleLeft.setAlignment(HorizontalAlignment.LEFT);
            cellStyleLeft.setVerticalAlignment(VerticalAlignment.CENTER);

            setUpAuthority(exchange, lfRyyjsjQO);
            List<LfZtryyjEntity> data = this.getBaseMapper().getZdryExportData(lfRyyjsjQO);
            Map<String, List<LfZtryyjEntity>> map = data.stream().collect(Collectors.groupingBy(LfZtryyjEntity::getYjlx));

            if (null != map.get("tldp")) {
                if (map.get("tldp").size() > 0) {
                    List<String> tldpEntities = map.get("tldp").stream().map(LfZtryyjEntity::getGlId).collect(Collectors.toList());
                    //数据过多时分批查询
                    List<TKmTldpv2Entity> tKmTldpEntityList = new ArrayList<>();
                    if (null != tldpEntities && tldpEntities.size() > LIST_SIZE) {
                        List<List<String>> partitionList = ListUtils.partition(tldpEntities, LIST_SIZE);
                        for (List<String> tldpEntitie : partitionList) {
                            List<TKmTldpv2Entity> tKmTldpEntityLists = tKmTldpv2Service.getTldpEntityList(tldpEntitie);
                            tKmTldpEntityList.addAll(tKmTldpEntityLists);
                        }
                    } else {
                        List<TKmTldpv2Entity> tKmTldpEntityLists = tKmTldpv2Service.getTldpEntityList(tldpEntities);
                        tKmTldpEntityList.addAll(tKmTldpEntityLists);
                    }
                    log.info("find tldp total" + tKmTldpEntityList.size());
                    Map<String, String> proTitleMap = JsonFileParseUtil.readJsonFromClassPath("json/tldp.json", Map.class);
                    ExeclUtil.genExcel(wb, cellStyleCenter, cellStyleLeft, tKmTldpEntityList, TKmTldpv2Entity.class, proTitleMap, "铁路订票");
                }
            }
            if (null != map.get("wbsw")) {
                if (map.get("wbsw").size() > 0) {
                    List<String> wbswEntities = map.get("wbsw").stream().map(LfZtryyjEntity::getGlId).collect(Collectors.toList());
                    //数据过多时分批查询
                    List<TKmWbswEntity> tKmWbswEntityList = new ArrayList<>();
                    if (null != wbswEntities && wbswEntities.size() > LIST_SIZE) {
                        List<List<String>> partitionList = ListUtils.partition(wbswEntities, LIST_SIZE);
                        for (List<String> wbswEntitie : partitionList) {
                            List<TKmWbswEntity> tKmWbswEntityLists = tKmWbswService.getWbswList(wbswEntitie);
                            tKmWbswEntityList.addAll(tKmWbswEntityLists);
                        }
                    } else {
                        List<TKmWbswEntity> tKmWbswEntityLists = tKmWbswService.getWbswList(wbswEntities);
                        tKmWbswEntityList.addAll(tKmWbswEntityLists);
                    }
                    log.info("find wbsw total" + tKmWbswEntityList.size());
                    Map<String, String> proTitleMap = JsonFileParseUtil.readJsonFromClassPath("json/wbsw.json", Map.class);
                    ExeclUtil.genExcel(wb, cellStyleCenter, cellStyleLeft, tKmWbswEntityList, TKmWbswEntity.class, proTitleMap, "网吧上网");
                }
            }
            if (null != map.get("lgzs")) {
                if (map.get("lgzs").size() > 0) {
                    List<String> lgzsEntities = map.get("lgzs").stream().map(LfZtryyjEntity::getGlId).collect(Collectors.toList());
                    //数据过多时分批查询
                    List<TKmLgzsEntity> lgzsEntityList = new ArrayList<>();
                    if (null != lgzsEntities && lgzsEntities.size() > LIST_SIZE) {
                        List<List<String>> partitionList = ListUtils.partition(lgzsEntities, LIST_SIZE);
                        for (List<String> lgzsEntitie : partitionList) {
                            List<TKmLgzsEntity> lgzsEntityLists = tKmLgzsService.getLgzsList(lgzsEntitie);
                            lgzsEntityList.addAll(lgzsEntityLists);
                        }
                    } else {
                        List<TKmLgzsEntity> lgzsEntityLists = tKmLgzsService.getLgzsList(lgzsEntities);
                        lgzsEntityList.addAll(lgzsEntityLists);
                    }
                    log.info("find lgzs total" + lgzsEntityList.size());
                    Map<String, String> proTitleMap = JsonFileParseUtil.readJsonFromClassPath("json/lgzs.json", Map.class);
                    ExeclUtil.genExcel(wb, cellStyleCenter, cellStyleLeft, lgzsEntityList, TKmLgzsEntity.class, proTitleMap, "旅馆住宿");
                }
            }
            if (null != map.get("mhdz")) {
                if (map.get("mhdz").size() > 0) {
                    List<String> mhdzEntities = map.get("mhdz").stream().map(LfZtryyjEntity::getGlId).collect(Collectors.toList());
                    //数据过多时分批查询
                    List<TKmMhdzEntity> mhdzEntityList = new ArrayList<>();
                    if (null != mhdzEntities && mhdzEntities.size() > LIST_SIZE) {
                        List<List<String>> partitionList = ListUtils.partition(mhdzEntities, LIST_SIZE);
                        for (List<String> mhdzEntitie : partitionList) {
                            List<TKmMhdzEntity> mhdzEntityLists = tKmMhdzService.getMhdzList(mhdzEntitie);
                            mhdzEntityList.addAll(mhdzEntityLists);
                        }
                    } else {
                        List<TKmMhdzEntity> mhdzEntityLists = tKmMhdzService.getMhdzList(mhdzEntities);
                        mhdzEntityList.addAll(mhdzEntityLists);
                    }
                    log.info("find mhdz total" + mhdzEntityList.size());
                    Map<String, String> proTitleMap = JsonFileParseUtil.readJsonFromClassPath("json/mhdz.json", Map.class);
                    ExeclUtil.genExcel(wb, cellStyleCenter, cellStyleLeft, mhdzEntityList, TKmMhdzEntity.class, proTitleMap, "民航订座");
                }
            }
            if (null != map.get("mhlg")) {
                if (map.get("mhlg").size() > 0) {
                    List<String> mhlgEntities = map.get("mhlg").stream().map(LfZtryyjEntity::getGlId).collect(Collectors.toList());
                    //数据过多时分批查询
                    List<TKmMhlgEntity> mhlgEntityList = new ArrayList<>();
                    if (null != mhlgEntities && mhlgEntities.size() > LIST_SIZE) {
                        List<List<String>> partitionList = ListUtils.partition(mhlgEntities, LIST_SIZE);
                        for (List<String> mhdzEntitie : partitionList) {
                            List<TKmMhlgEntity> mhlgEntityLists = tKmMhlgService.getMhlgList(mhdzEntitie);
                            mhlgEntityList.addAll(mhlgEntityLists);
                        }
                    } else {
                        List<TKmMhlgEntity> mhlgEntityLists = tKmMhlgService.getMhlgList(mhlgEntities);
                        mhlgEntityList.addAll(mhlgEntityLists);
                    }
                    log.info("find mhlg total" + mhlgEntityList.size());
                    Map<String, String> proTitleMap = JsonFileParseUtil.readJsonFromClassPath("json/mhlg.json", Map.class);
                    ExeclUtil.genExcel(wb, cellStyleCenter, cellStyleLeft, mhlgEntityList, TKmMhlgEntity.class, proTitleMap, "民航离港");
                }
            }
            if (null != map.get("glky-gp")) {
                if (map.get("glky-gp").size() > 0) {
                    List<String> glkyEntities = map.get("glky-gp").stream().map(LfZtryyjEntity::getGlId).collect(Collectors.toList());
                    //数据过多时分批查询
                    List<TKmGlkygpEntity> glkygpEntityList = new ArrayList<>();
                    if (null != glkyEntities && glkyEntities.size() > LIST_SIZE) {
                        List<List<String>> partitionList = ListUtils.partition(glkyEntities, LIST_SIZE);
                        for (List<String> glkyEntitie : partitionList) {
                            List<TKmGlkygpEntity> glkygpEntityLists = tKmGlkygpService.getGlkygpList(glkyEntitie);
                            glkygpEntityList.addAll(glkygpEntityLists);
                        }
                    } else {
                        List<TKmGlkygpEntity> glkygpEntityLists = tKmGlkygpService.getGlkygpList(glkyEntities);
                        glkygpEntityList.addAll(glkygpEntityLists);
                    }
                    log.info("find glky-gp total" + glkygpEntityList.size());
                    Map<String, String> proTitleMap = JsonFileParseUtil.readJsonFromClassPath("json/glkygp.json", Map.class);
                    ExeclUtil.genExcel(wb, cellStyleCenter, cellStyleLeft, glkygpEntityList, TKmGlkygpEntity.class, proTitleMap, "公路客运订票");
                }
            }
            if (null != map.get("phyj")) {
                if (map.get("phyj").size() > 0) {
                    List<String> phyjes = map.get("phyj").stream().map(LfZtryyjEntity::getGlId).collect(Collectors.toList());
                    //数据过多时分批查询
                    List<KmPhYjEntity> phYjEntities = new ArrayList<>();
                    if (null != phyjes && phyjes.size() > LIST_SIZE) {
                        List<List<String>> partitionList = ListUtils.partition(phyjes, LIST_SIZE);
                        for (List<String> phyje : partitionList) {
                            List<KmPhYjEntity> phYjEntitie = kmPhYjService.list(new QueryWrapper<KmPhYjEntity>().lambda().in(KmPhYjEntity::getAlarmId, phyje));
                            phYjEntities.addAll(phYjEntitie);
                        }
                    } else {
                        List<KmPhYjEntity> phYjEntitie = kmPhYjService.list(new QueryWrapper<KmPhYjEntity>().lambda().in(KmPhYjEntity::getAlarmId, phyjes));
                        phYjEntities.addAll(phYjEntitie);
                    }
                    log.info("find phyj total" + phYjEntities.size());
                    Map<String, String> proTitleMap = JsonFileParseUtil.readJsonFromClassPath("json/phyj.json", Map.class);
                    ExeclUtil.genExcel(wb, cellStyleCenter, cellStyleLeft, phYjEntities, KmPhYjEntity.class, proTitleMap, "手机预警");
                }
            }
            if (null != map.get("rlsb")) {
                if (map.get("rlsb").size() > 0) {
                    List<String> rlsbes = map.get("rlsb").stream().map(LfZtryyjEntity::getGlId).collect(Collectors.toList());
                    //数据过多时分批查询
                    List<KmRlsbEntity> rlsbEntities = new ArrayList<>();
                    if (null != rlsbes && rlsbes.size() > LIST_SIZE) {
                        List<List<String>> partitionList = ListUtils.partition(rlsbes, LIST_SIZE);
                        for (List<String> rlsbe : partitionList) {
                            List<KmRlsbEntity> rlsbEntitie = kmRlsbService.list(new QueryWrapper<KmRlsbEntity>().lambda().in(KmRlsbEntity::getNotificationID, rlsbe));
                            rlsbEntities.addAll(rlsbEntitie);
                        }
                    } else {
                        List<KmRlsbEntity> rlsbEntitie = kmRlsbService.list(new QueryWrapper<KmRlsbEntity>().lambda().in(KmRlsbEntity::getNotificationID, rlsbes));
                        rlsbEntities.addAll(rlsbEntitie);
                    }
                    log.info("find rlsb total" + rlsbEntities.size());
                    Map<String, String> proTitleMap = JsonFileParseUtil.readJsonFromClassPath("json/rlsb.json", Map.class);
                    ExeclUtil.genExcel(wb, cellStyleCenter, cellStyleLeft, rlsbEntities, KmRlsbEntity.class, proTitleMap, "人脸识别预警");
                }
            }
            wb.write(outputStream);
        } catch (IOException e) {
            log.error("导出execl时发生异常，异常为==>{}", e.getMessage());
            throw e;
        } finally {
            try {
                wb.close();
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                log.error("error == >{}", e.getMessage());
            }
        }
        return Mono.just(dataBuffer);
    }

    @Override
    public List<String> findWebsocketPsuhUserListByYjwybs(String refId) {
        try {
            List<String> gkjbs = Arrays.asList("高", "中", "低");
            List<String> resultList = new ArrayList<>();
            List<UserTypeInfo> users = new ArrayList<>();  //当前链接websocket的所有用户
            Set<String> keies = redisUtil.keys("kmzdry_websocket_*");
            for (String key : keies) {
                String s = redisUtil.get(key).toString();
                users.add(getUserTypeInfo(s));
            }
            Map<String, String> result = this.getBaseMapper().getZdryInfoByYjwybs(refId);
            // 查询相关的责任部门
            List<String> zrbms = null;
            if (result.containsKey("id") && null != result.get("id")) {
                zrbms = kmZdryTypeService.list(new QueryWrapper<KmZdryTypeEntity>().lambda()
                        .eq(KmZdryTypeEntity::getZdryId, result.get("id"))).stream().map(KmZdryTypeEntity::getZrbm).collect(Collectors.toList());
            }
            //角色消息分发规则：
            // 1 2 5 警种
            // 3 6   分局用户
            // 4     派出所用户
            for (UserTypeInfo u : users) {
                if (u.getRole() == null) continue;
                // 判断是不是情报中心
                switch (u.getRole()) {
                    case "1":
                        resultList.add(u.getToken());
                        break; // 情报中心
                    case "2": { //警种
                        if (result.containsKey("gkjb") && gkjbs.contains(result.get("gkjb"))) {
                            if (null != zrbms && zrbms.size() > 0) {
                                if (zrbms.equals(result.get("zrbm")))
                                    resultList.add(u.getToken());
                            }
                        }
                    }
                    break;
                    case "3": { // 分局
                        if (result.containsKey("gkjb") && gkjbs.contains(result.get("gkjb"))) {
                            if (null != result.get("ssxq")) {
                                if (result.get("ssxq").equals(u.getName())) resultList.add(u.getToken());
                            }
                        }
                    }
                    break;
                    case "4": { //派出所
                        if (result.containsKey("gkjb") && gkjbs.contains(result.get("gkjb"))) {
                            if (null != result.get("sspcs")) {
                                if (result.get("sspcs").equals(u.getName())) resultList.add(u.getToken());
                            }
                        }
                    }
                    break;
                    case "5": { //警种(查阅)
                        if (result.containsKey("gkjb") && gkjbs.contains(result.get("gkjb"))) {
                            if (null != zrbms && zrbms.size() > 0) {
                                if (zrbms.equals(result.get("zrbm"))) {
                                    resultList.add(u.getToken());
                                }

                            }
                        }
                    }
                    break;
                    case "6": { // 分局
                        if (result.containsKey("gkjb") && gkjbs.contains(result.get("gkjb"))) {
                            if (null != result.get("ssxq")) {
                                if (result.get("ssxq").equals(u.getName())) resultList.add(u.getToken());
                            }
                        }
                    }
                    break;
                    default:
                        resultList.add(u.getToken());
                        break;

                }
            }
            return resultList;
        } catch (Exception e) {
            log.error("查询推送token时发生异常：{}", e.getMessage());
            return null;
        }
    }


    private UserTypeInfo getUserTypeInfo(String s) {
        try {
            UserTypeInfo userTypeInfo = new UserTypeInfo();
            String[] array = s.substring(s.indexOf("{") + 1, s.lastIndexOf("}")).split(",");
            for (String obj : array) {
                switch (obj.split("=")[0].trim()) {
                    case "token":
                        userTypeInfo.setToken(obj.split("=")[1].trim());
                        break;
                    case "id":
                        userTypeInfo.setId(obj.split("=")[1].trim());
                        break;
                    case "role":
                        userTypeInfo.setRole(obj.split("=")[1].trim());
                        break;
                    case "name":
                        userTypeInfo.setName(obj.split("=")[1].trim());
                        break;
                }
            }
            return userTypeInfo;
        } catch (Exception e) {
            log.error("websocket 链接参数不正确。");
            return null;
        }
    }

    @Override
    public IPage<ZdryTxVo> queryLocationInfo(List<YjInfoParamQo> paramMap, Integer offset, Integer pageSize) {
        Page<ZdryTxVo> page = new Page<>(offset, pageSize);
        IPage<ZdryTxVo> result = null;
        try {
            if (paramMap != null) {
                result = this.getBaseMapper().queryLocationInfo(page, paramMap);
            }
            handleTableResultMap(result.getRecords());
        } catch (Exception e) {
            log.error("查询重点人员预警信息时发生异常：=====》{}", e.getMessage());
            return null;
        }
        return result;
    }


    /**
     * 处理撒点图的列表数据
     *
     * @param mapList
     */
    private void handleTableResultMap(List<ZdryTxVo> mapList) {
        try {
            for (ZdryTxVo map : mapList) {
                //判断预警类型，查询网吧上机和下机时间 或者 旅馆 入住 和 退房时间
                if (null != map.getYjlx()) {
                    if (map.getYjlx().equals("wbsw")) {
                        Map<String, Object> wb = tKmWbswService.findWbswStartAndEndTime(map.getWybs());
                        if (null != wb) {
                            if (wb.containsKey("startTime") && wb.get("startTime").toString().length() > 0) {
                                map.setStartTime(wb.get("startTime").toString());
                            }
                            if (wb.containsKey("endTime") && wb.get("endTime").toString().length() > 0) {
                                map.setEndTime(wb.get("endTime").toString());
                            }
                        }
                    } else if (map.getYjlx().equals("lgzs")) {
                        Map<String, Object> lg = tKmLgzsService.findLgzsStartAndEndTime(map.getWybs());
                        if (null != lg) {
                            if (lg.containsKey("startTime") && lg.get("startTime").toString().length() > 0) {
                                map.setStartTime(lg.get("startTime").toString());
                            }
                            if (lg.containsKey("endTime") && lg.get("endTime").toString().length() > 0) {
                                map.setEndTime(DateUtils.convertStrDateToOtherStr(lg.get("endTime").toString(), "yyyy/MM/dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss"));
                            }
                        }
                    }
                }
                if (map.getYjczlb() != null) {
                    SysDictEntity yjczlbdictEntity = iSysDictService.getEntityByKey("zdry_yjczlb", map.getYjczlb());
                    if (null != yjczlbdictEntity)
                        map.setYjczlbName(yjczlbdictEntity.getValue());
                }
                if (map.getRysx() != null) {
                    SysDictEntity rysxdictEntity = iSysDictService.getEntityByKey("zdry_ryxx", map.getRysx());
                    if (null != rysxdictEntity)
                        map.setRysx(rysxdictEntity.getValue());
                }

                List<KmZdryTypeEntity> zdryTypes = kmZdryTypeService.list(new QueryWrapper<KmZdryTypeEntity>().lambda().eq(KmZdryTypeEntity::getZdryId, map.getZdryId()));
                if (zdryTypes != null && zdryTypes.size() > 0) {
                    StringBuilder rylbx = new StringBuilder();
                    StringBuilder xl = new StringBuilder();
                    zdryTypes.forEach(e -> {
                        if (rylbx.length() > 0) {
                            rylbx.append("/").append(e.getRylb());
                        } else rylbx.append(e.getRylb());
                        if (xl.length() > 0) {
                            xl.append("/").append(e.getXl());
                        } else xl.append(e.getXl());
                    });
                    map.setRylbx(rylbx.toString());
                    map.setXl(xl.toString());
                }
                // 处理预警类型
                if (map.getYjlx() != null) {
                    map.setYjlx(ZdryYjLx.YJLX.get(map.getYjlx()));
                }
            }
        } catch (Exception e) {
            log.error("处理数据是发生异常异常：======> {}", e.getMessage());
        }
    }

    /**
     * 处理撒点图的列表数据
     *
     * @param mapList
     */
    private void handleResultMap(List<ZdryTxVo> mapList) {
        try {
            for (ZdryTxVo map : mapList) {
                //判断预警类型，查询网吧上机和下机时间 或者 旅馆 入住 和 退房时间
                if (null != map.getYjlx()) {
                    if (map.getYjlx().equals("wbsw")) {
                        Map<String, Object> wb = tKmWbswService.findWbswStartAndEndTime(map.getWybs());
                        if (null != wb) {
                            if (wb.containsKey("startTime") && wb.get("startTime").toString().length() > 0) {
                                map.setStartTime(wb.get("startTime").toString());
                            }
                            if (wb.containsKey("endTime") && wb.get("endTime").toString().length() > 0) {
                                map.setEndTime(wb.get("endTime").toString());
                            }
                        }
                    } else if (map.getYjlx().equals("lgzs")) {
                        Map<String, Object> lg = tKmLgzsService.findLgzsStartAndEndTime(map.getWybs());
                        if (null != lg) {
                            if (lg.containsKey("startTime") && lg.get("startTime").toString().length() > 0) {
                                map.setStartTime(lg.get("startTime").toString());
                            }
                            if (lg.containsKey("endTime") && lg.get("endTime").toString().length() > 0) {
                                map.setEndTime(DateUtils.convertStrDateToOtherStr(lg.get("endTime").toString(), "yyyy/MM/dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss"));
                            }
                        }
                    }
                }
                if (map.getYjczlb() != null) {
                    SysDictEntity yjczlbdictEntity = iSysDictService.getEntityByKey("zdry_yjczlb", map.getYjczlb());
                    if (null != yjczlbdictEntity)
                        map.setYjczlbName(yjczlbdictEntity.getValue());
                }
                if (map.getRysx() != null) {
                    SysDictEntity rysxdictEntity = iSysDictService.getEntityByKey("zdry_ryxx", map.getRysx());
                    if (null != rysxdictEntity)
                        map.setRysx(rysxdictEntity.getValue());
                }
                if (map.getTypes() != null && map.getTypes().size() > 0) {
                    StringBuilder rylbx = new StringBuilder();
                    StringBuilder xl = new StringBuilder();
                    map.getTypes().forEach(e -> {
                        if (rylbx.length() > 0) {
                            rylbx.append("/").append(e.getRylb());
                        } else rylbx.append(e.getRylb());
                        if (xl.length() > 0) {
                            xl.append("/").append(e.getXl());
                        } else xl.append(e.getXl());
                    });
                    map.setRylbx(rylbx.toString());
                    map.setXl(xl.toString());
                }
                // 处理预警类型
                if (map.getYjlx() != null) {
                    map.setYjlx(ZdryYjLx.YJLX.get(map.getYjlx()));
                }

                StringBuilder sb = new StringBuilder();
                if (null != map.getYjdSsfj() && map.getYjdSsfj().length() > 0) {
                    sb.append(map.getYjdSsfj());
                }
                if (null != map.getYjdPcs() && map.getYjdPcs().length() > 0) {
                    if (sb.length() > 0) sb.append("(").append(map.getYjdPcs()).append(")");
                    else sb.append(map.getYjdPcs());
                }
                if (sb.length() > 0) map.setCurrentPosition(sb.toString());
            }
        } catch (Exception e) {
            log.error("处理数据是发生异常异常：======> {}", e.getMessage());
        }
    }

    @Override
    public Mono<DataBuffer> exportYjLocationInfo(List<YjInfoParamQo> paramMap, String exportName) {
        DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory().allocateBuffer();
        OutputStream outputStream = dataBuffer.asOutputStream();
        // 每次写100行数据，就刷新数据出缓存
        SXSSFWorkbook wb = new SXSSFWorkbook(100);

        try {
            CellStyle cellStyleCenter = wb.createCellStyle();
            CellStyle cellStyleLeft = wb.createCellStyle();
            cellStyleCenter.setAlignment(HorizontalAlignment.CENTER); // 居中
            cellStyleCenter.setVerticalAlignment(VerticalAlignment.CENTER); // 居中
            cellStyleLeft.setAlignment(HorizontalAlignment.LEFT);
            cellStyleLeft.setVerticalAlignment(VerticalAlignment.CENTER);

            List<ZdryTxVo> data = this.getBaseMapper().queryExportLocationInfo(paramMap);
            handleResultMap(data);
            Map<String, String> proTitleMap = JsonFileParseUtil.readJsonFromClassPath("json/yjlocation.json", Map.class);
            ExeclUtil.genExcel(wb, cellStyleCenter, cellStyleLeft, data, ZdryTxVo.class, proTitleMap, "重点人员预警信息");
            wb.write(outputStream);
        } catch (Exception e) {
            log.error("导出execl时发生异常：======>{}", e.getMessage());
        } finally {
            try {
                wb.close();
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                log.error("关闭流时发生异常：======> {}", e.getMessage());
            }
        }
        return Mono.just(dataBuffer);
    }

    @Override
    public IPage<ZdryTxVo> queryTlKyMhQxInfo(LfRyyjsjQO lfRyyjsjQO, ZdryQxzkUtilBean zdryQxzkUtilBean, Integer offset, Integer pagesize, ServerWebExchange exchange) {
        Page<ZdryTxVo> page = new Page<>(offset, pagesize);
        setUpAuthority(exchange, lfRyyjsjQO);
        // 判断 云南省内 云南省外 提升查询效率
        if (zdryQxzkUtilBean.getSendPro().equals("云南省") || zdryQxzkUtilBean.getSendPro().equals("云南")) {
            zdryQxzkUtilBean.setSendPro(null);
        } else {
            zdryQxzkUtilBean.setSendCity(null);
        }
        if (zdryQxzkUtilBean.getEndPro().equals("云南省") || zdryQxzkUtilBean.getEndPro().equals("云南")) {
            zdryQxzkUtilBean.setEndPro(null);
        } else {
            zdryQxzkUtilBean.setEndCity(null);
        }
        List<ZdryQxzkUtilBean> param = new ArrayList<>();
        if (zdryQxzkUtilBean.getYjlxs() != null && zdryQxzkUtilBean.getYjlxs().size() > 0) {
            zdryQxzkUtilBean.getYjlxs().forEach(e -> {
                ZdryQxzkUtilBean temp = new ZdryQxzkUtilBean(zdryQxzkUtilBean.getSendPro(), zdryQxzkUtilBean.getSendCity(),
                        zdryQxzkUtilBean.getEndPro(), zdryQxzkUtilBean.getEndCity());
                if (e.indexOf("$") > 0) {
                    List<String> lx = Arrays.stream(e.split("\\$")).collect(Collectors.toList());
                    temp.setYjlx(lx.get(0));
                    temp.setInOut(Integer.parseInt(lx.get(1)));
                } else {
                    temp.setYjlx(e);
                    temp.setInOut(null);
                }
                param.add(temp);
            });
        }
        IPage<ZdryTxVo> result = this.getBaseMapper().queryTlKyMhQxInfo(page, lfRyyjsjQO, param);
        handleTableResultMap(result.getRecords());
        return result;
    }

    @Override
    public Mono<DataBuffer> exportYjTxInfo(LfRyyjsjQO lfRyyjsjQO, ZdryQxzkUtilBean zdryQxzkUtilBean, ServerWebExchange exchange) {
//        //处理进出标志的参数
//        Map<String,Object> map = new HashMap<>();
//        List<String> yjlbxs = lfRyyjsjQO.getYjlbxs();
//        List<Map<String, Object>> inOut = new ArrayList<>();
//        for(String yjlx : yjlbxs){
//            if("mhdz".equals(yjlx) || "mhlg".equals(yjlx)){
//                map.put("yjlx","mhdz,mhlg");
//            }else if("glky-gp".equals(yjlx)){
//                map.put("yjlx","glky-gp");
//            }else if("tldp".equals(yjlx)){
//                map.put("yjlx","tldp");
//            } else {
//                if("0".equals(yjlx)){
//                    map.put("inOut","1,2");
//                }else {
//                    map.put("inOut",yjlx);
//                }
//
//            }
//        }
//        inOut.add(map);
//        lfRyyjsjQO.setInOut(inOut);

        DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory().allocateBuffer();
        OutputStream outputStream = dataBuffer.asOutputStream();
        // 每次写100行数据，就刷新数据出缓存
        SXSSFWorkbook wb = new SXSSFWorkbook(100);

        try {
            CellStyle cellStyleCenter = wb.createCellStyle();
            CellStyle cellStyleLeft = wb.createCellStyle();
            cellStyleCenter.setAlignment(HorizontalAlignment.CENTER); // 居中
            cellStyleCenter.setVerticalAlignment(VerticalAlignment.CENTER); // 居中
            cellStyleLeft.setAlignment(HorizontalAlignment.LEFT);
            cellStyleLeft.setVerticalAlignment(VerticalAlignment.CENTER);

            // 判断 云南省内 云南省外 提升查询效率
            if (zdryQxzkUtilBean.getSendPro().equals("云南省") || zdryQxzkUtilBean.getSendPro().equals("云南")) {
                zdryQxzkUtilBean.setSendPro(null);
            } else {
                zdryQxzkUtilBean.setSendCity(null);
            }
            if (zdryQxzkUtilBean.getEndPro().equals("云南省") || zdryQxzkUtilBean.getEndPro().equals("云南")) {
                zdryQxzkUtilBean.setEndPro(null);
            } else {
                zdryQxzkUtilBean.setEndCity(null);
            }
            List<ZdryQxzkUtilBean> param = new ArrayList<>();
            if (zdryQxzkUtilBean.getYjlxs() != null && zdryQxzkUtilBean.getYjlxs().size() > 0) {
                zdryQxzkUtilBean.getYjlxs().forEach(e -> {
                    ZdryQxzkUtilBean temp = new ZdryQxzkUtilBean(zdryQxzkUtilBean.getSendPro(), zdryQxzkUtilBean.getSendCity(),
                            zdryQxzkUtilBean.getEndPro(), zdryQxzkUtilBean.getEndCity());
                    if (e.indexOf("$") > 0) {
                        List<String> lx = Arrays.stream(e.split("\\$")).collect(Collectors.toList());
                        temp.setYjlx(lx.get(0));
                        temp.setInOut(Integer.parseInt(lx.get(1)));
                    } else {
                        temp.setYjlx(e);
                        temp.setInOut(null);
                    }
                    param.add(temp);
                });
            }

            setUpAuthority(exchange, lfRyyjsjQO);
            List<ZdryTxVo> data = this.getBaseMapper().exportYjTxInfo(lfRyyjsjQO, param);
            handleResultMap(data);

            Map<String, String> proTitleMap = JsonFileParseUtil.readJsonFromClassPath("json/yjtx.json", Map.class);
            ExeclUtil.genExcel(wb, cellStyleCenter, cellStyleLeft, data, ZdryTxVo.class, proTitleMap, "重点人员预警迁徙信息");
            wb.write(outputStream);
        } catch (Exception e) {
            log.error("导出execl时发生异常：======>{}", e.getMessage());
        } finally {
            try {
                wb.close();
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                log.error("关闭流时发生异常：======> {}", e.getMessage());
            }
        }
        return Mono.just(dataBuffer);
    }


    @Override
    public Map<String, Object> pushZdryYjInfo(Integer offset, Integer pageSize) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            Page<LfZtryyjEntity> page = new Page<>(offset, pageSize);
            IPage<LfZtryyjEntity> resultPage = this.page(page);
            resultMap.put("total", resultPage.getTotal());
            List<Map<String, Object>> records = new ArrayList<>();
            for (LfZtryyjEntity z : resultPage.getRecords()) {
                Map<String, Object> map = new HashMap<>();
                map.put("type", ZdryYjLx.YJLX.get(z.getYjlx()));
                map.put("address", z.getYjdd());
                map.put("lng", z.getX());
                map.put("lat", z.getY());
                map.put("time", z.getYjsj());
                map.put("IDCard", z.getYjbs());
                map.put("person", z.getRyxm());
                map.put("handleFlag", z.getHandleFlag() == null ? "未处置" : z.getHandleFlag() == 1 ? "未处置" : "已处置");
                if (z.getYjlx().equals(ZdryYjLx.LGZS) && z.getGlId() != null) {
                    TKmLgzsEntity lgzs = tKmLgzsService.getByGlId(z.getGlId());
                    if (null != lgzs)
                        map.put("roomNumber", lgzs.getRuzhufanghao());
                }
                records.add(map);
            }
            resultMap.put("records", records);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("推送接口后台的异常为======> {}", e.getMessage());
        }
        return resultMap;
    }

    @Override
    @Transactional
    public List<ZdryYjPushToDsUtil> queryYjDataPushToDs() {
        // 铁路之外的预警 超时时间12个小时
        List<ZdryYjPushDataVo> data = this.getBaseMapper().queryYjDataPushToDs();
        // 铁路 超时时间72个小时
        List<ZdryYjPushDataVo> tldpData = this.getBaseMapper().queryTldpYjDataPushToDs();

        data.addAll(tldpData);

        //查询出来的数据符合以下条件才推送
        List<ZdryYjPushToDsUtil> result = handleAssist(data);
        //只改变实际已经发送的数据的send_falg状态
        if (null != result && result.size() > 0) {
            this.getBaseMapper().updateYjSendFlag(result.stream().map(ZdryYjPushToDsUtil::getAlarmId).collect(Collectors.toList()));
        }
        return result;
    }

    @Override
    public Object zdryYjStatistics(LfRyyjsjQO lfRyyjsjQO, ServerWebExchange exchange) {

        setUpAuthority(exchange, lfRyyjsjQO);
        List<ZdryYjStatisticsVo> orData = this.getBaseMapper().zdryYjStatistics(lfRyyjsjQO);

        // 统计情报中心的数据
        ZdryYjStatisticsVo qbzx = new ZdryYjStatisticsVo();
        handYjStatistics(qbzx, orData);

        if (null != qbzx.getChild() && qbzx.getChild().size() > 0) {
            for (ZdryYjStatisticsVo ssxq : qbzx.getChild()) {
                List<ZdryYjStatisticsVo> sspcses = orData.stream().filter(e -> e.getSsxqId().equals(ssxq.getSsxqId())).collect(Collectors.toList());
                Map<String, List<ZdryYjStatisticsVo>> pcsMap = sspcses.stream().collect(Collectors.groupingBy(ZdryYjStatisticsVo::getSspcsId));
                List<ZdryYjStatisticsVo> childList = new ArrayList<>();
                for (String pcsId : pcsMap.keySet()) {
                    List<ZdryYjStatisticsVo> pcsList = pcsMap.get(pcsId);
                    ZdryYjStatisticsVo pcs = new ZdryYjStatisticsVo();
                    for (ZdryYjStatisticsVo p : pcsList) {
                        pcs.setSspcsId(p.getSspcsId());
                        pcs.setSspcs(p.getSspcs());

                        pcs.setTotal(pcs.getTotal() + p.getTotal());
                        pcs.setPersonCount(pcs.getPersonCount() + p.getPersonCount());
                        pcs.setHandleTotal(pcs.getHandleTotal() + p.getHandleTotal());

                        pcs.setTldpCount(pcs.getTldpCount() + p.getTldpCount());
                        pcs.setTldpPersonCount(pcs.getTldpPersonCount() + p.getTldpPersonCount());
                        pcs.setTldpHandleCount(pcs.getTldpHandleCount() + p.getTldpHandleCount());

                        pcs.setWbswCount(pcs.getWbswCount() + p.getWbswCount());
                        pcs.setWbswPersonCount(pcs.getWbswPersonCount() + p.getWbswPersonCount());
                        pcs.setWbswHandleCount(pcs.getWbswHandleCount() + p.getWbswHandleCount());

                        pcs.setLgzsCount(pcs.getLgzsCount() + p.getLgzsCount());
                        pcs.setLgzsPersonCount(pcs.getLgzsPersonCount() + p.getLgzsPersonCount());
                        pcs.setLgzsHandleCount(pcs.getLgzsHandleCount() + p.getLgzsHandleCount());

                        pcs.setMhdzCount(pcs.getMhdzCount() + p.getMhdzCount());
                        pcs.setMhdzPersonCount(pcs.getMhdzPersonCount() + p.getMhdzPersonCount());
                        pcs.setMhdzHandleCount(pcs.getMhdzHandleCount() + p.getMhdzHandleCount());

                        pcs.setMhlgCount(pcs.getMhlgCount() + p.getMhlgCount());
                        pcs.setMhlgPersonCount(pcs.getMhlgPersonCount() + p.getMhlgPersonCount());
                        pcs.setMhlgHandleCount(pcs.getMhlgHandleCount() + p.getMhlgHandleCount());

                        pcs.setGlkyCount(pcs.getGlkyCount() + p.getGlkyCount());
                        pcs.setGlkyPersonCount(pcs.getGlkyPersonCount() + p.getGlkyPersonCount());
                        pcs.setGlkyHandleCount(pcs.getGlkyHandleCount() + p.getGlkyHandleCount());

                        pcs.setPhyjCount(pcs.getPhyjCount() + p.getPhyjCount());
                        pcs.setPhyjPersonCount(pcs.getPhyjPersonCount() + p.getPhyjPersonCount());
                        pcs.setPhyjHandleCount(pcs.getPhyjHandleCount() + p.getPhyjHandleCount());

                        pcs.setRlsbCount(pcs.getRlsbCount() + p.getRlsbCount());
                        pcs.setRlsbPersonCount(pcs.getRlsbPersonCount() + p.getRlsbPersonCount());
                        pcs.setRlsbHandleCount(pcs.getRlsbHandleCount() + p.getRlsbHandleCount());
                    }
                    List<ZdryYjStatisticsVo> gkmj = orData.stream().filter(e -> e.getSspcsId().equals(pcs.getSspcsId())).collect(Collectors.toList());
                    pcs.setChild(gkmj);
                    childList.add(pcs);
                }
                ssxq.setChild(childList);
            }
        }
        return qbzx;
    }

    @Override
    public IPage<ZdryTxVo> queryZdryYjStatisticsData(LfRyyjsjQO lfRyyjsjQO, ServerWebExchange exchange) {
        setUpAuthority(exchange, lfRyyjsjQO);
        Page<ZdryTxVo> page = new Page<>(lfRyyjsjQO.getStart(), lfRyyjsjQO.getSize());
        IPage<ZdryTxVo> result = this.getBaseMapper().queryZdryYjStatisticsData(page, lfRyyjsjQO);
        handleTableResultMap(result.getRecords());
        return result;
    }

    @Override
    public Mono<DataBuffer> exportZdryYjStatisticsData(LfRyyjsjQO lfRyyjsjQO, ServerWebExchange exchange) {
        DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory().allocateBuffer();
        OutputStream outputStream = dataBuffer.asOutputStream();
        // 每次写100行数据，就刷新数据出缓存
        SXSSFWorkbook wb = new SXSSFWorkbook(100);

        try {
            CellStyle cellStyleCenter = wb.createCellStyle();
            CellStyle cellStyleLeft = wb.createCellStyle();
            cellStyleCenter.setAlignment(HorizontalAlignment.CENTER); // 居中
            cellStyleCenter.setVerticalAlignment(VerticalAlignment.CENTER); // 居中
            cellStyleLeft.setAlignment(HorizontalAlignment.LEFT);
            cellStyleLeft.setVerticalAlignment(VerticalAlignment.CENTER);

            setUpAuthority(exchange, lfRyyjsjQO);
            List<ZdryTxVo> data = this.getBaseMapper().exportZdryYjStatisticsData(lfRyyjsjQO);
            handleResultMap(data);

            Map<String, String> proTitleMap = JsonFileParseUtil.readJsonFromClassPath("json/yjtx.json", Map.class);
            ExeclUtil.genExcel(wb, cellStyleCenter, cellStyleLeft, data, ZdryTxVo.class, proTitleMap, "重点人员预警统计数据");
            wb.write(outputStream);
        } catch (Exception e) {
            log.error("导出execl时发生异常：======>{}", e.getMessage());
        } finally {
            try {
                wb.close();
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                log.error("关闭流时发生异常：======> {}", e.getMessage());
            }
        }
        return Mono.just(dataBuffer);
    }


    /**
     * result 返回的结果
     * data 数据范围
     * 处理预警统计数据
     */
    private void handYjStatistics(ZdryYjStatisticsVo result, List<ZdryYjStatisticsVo> data) {
        Map<String, List<ZdryYjStatisticsVo>> map = data.stream().collect(Collectors.groupingBy(ZdryYjStatisticsVo::getSsxqId));
        List<ZdryYjStatisticsVo> qbzxChild = new ArrayList<>();
        for (String ssxqId : map.keySet()) {
            ZdryYjStatisticsVo ssxq = new ZdryYjStatisticsVo();
            List<ZdryYjStatisticsVo> ssxqList = map.get(ssxqId);
            for (ZdryYjStatisticsVo fj : ssxqList) {
                ssxq.setSsxqId(fj.getSsxqId());
                ssxq.setSsxq(fj.getSsxq());

                result.setTotal(result.getTotal() + fj.getTotal());
                result.setPersonCount(result.getPersonCount() + fj.getPersonCount());
                result.setHandleTotal(result.getHandleTotal() + fj.getHandleTotal());
                ssxq.setTotal(ssxq.getTotal() + fj.getTotal());
                ssxq.setPersonCount(ssxq.getPersonCount() + fj.getPersonCount());
                ssxq.setHandleTotal(ssxq.getHandleTotal() + fj.getHandleTotal());

                result.setTldpCount(result.getTldpCount() + fj.getTldpCount());
                result.setTldpPersonCount(result.getTldpPersonCount() + fj.getTldpPersonCount());
                result.setTldpHandleCount(result.getTldpHandleCount() + fj.getTldpHandleCount());
                ssxq.setTldpCount(ssxq.getTldpCount() + fj.getTldpCount());
                ssxq.setTldpPersonCount(ssxq.getPersonCount() + fj.getTldpPersonCount());
                ssxq.setTldpHandleCount(ssxq.getTldpHandleCount() + fj.getTldpHandleCount());

                result.setWbswCount(result.getWbswCount() + fj.getWbswCount());
                result.setWbswPersonCount(result.getWbswPersonCount() + fj.getWbswPersonCount());
                result.setWbswHandleCount(result.getWbswHandleCount() + fj.getWbswHandleCount());
                ssxq.setWbswCount(ssxq.getWbswCount() + fj.getWbswCount());
                ssxq.setWbswPersonCount(ssxq.getWbswPersonCount() + fj.getWbswPersonCount());
                ssxq.setWbswHandleCount(ssxq.getWbswHandleCount() + fj.getWbswHandleCount());

                result.setLgzsCount(result.getLgzsCount() + fj.getLgzsCount());
                result.setLgzsPersonCount(result.getLgzsPersonCount() + fj.getLgzsPersonCount());
                result.setLgzsHandleCount(result.getLgzsHandleCount() + fj.getLgzsHandleCount());
                ssxq.setLgzsCount(ssxq.getLgzsCount() + fj.getLgzsCount());
                ssxq.setLgzsPersonCount(ssxq.getLgzsPersonCount() + fj.getLgzsPersonCount());
                ssxq.setLgzsHandleCount(ssxq.getLgzsHandleCount() + fj.getLgzsHandleCount());

                result.setMhdzCount(result.getMhdzCount() + fj.getMhdzCount());
                result.setMhdzPersonCount(result.getMhdzPersonCount() + fj.getMhdzPersonCount());
                result.setMhdzHandleCount(result.getMhdzHandleCount() + fj.getMhdzHandleCount());
                ssxq.setMhdzCount(ssxq.getMhdzCount() + fj.getMhdzCount());
                ssxq.setMhdzPersonCount(ssxq.getMhdzPersonCount() + fj.getMhdzPersonCount());
                ssxq.setMhdzHandleCount(ssxq.getMhdzHandleCount() + fj.getMhdzHandleCount());


                result.setMhlgCount(result.getMhlgCount() + fj.getMhlgCount());
                result.setMhlgPersonCount(result.getMhdzPersonCount() + fj.getMhlgPersonCount());
                result.setMhlgHandleCount(result.getMhlgHandleCount() + fj.getMhlgHandleCount());
                ssxq.setMhlgCount(ssxq.getMhlgCount() + fj.getMhlgCount());
                ssxq.setMhlgPersonCount(ssxq.getMhlgPersonCount() + fj.getMhlgPersonCount());
                ssxq.setMhlgHandleCount(ssxq.getMhlgHandleCount() + fj.getMhlgHandleCount());

                result.setGlkyCount(result.getGlkyCount() + fj.getGlkyCount());
                result.setGlkyPersonCount(result.getGlkyPersonCount() + fj.getGlkyPersonCount());
                result.setGlkyHandleCount(result.getGlkyHandleCount() + fj.getGlkyHandleCount());
                ssxq.setGlkyCount(ssxq.getGlkyCount() + fj.getGlkyCount());
                ssxq.setGlkyPersonCount(ssxq.getGlkyPersonCount() + fj.getGlkyPersonCount());
                ssxq.setGlkyHandleCount(ssxq.getGlkyHandleCount() + fj.getGlkyHandleCount());


                result.setPhyjCount(result.getPhyjCount() + fj.getPhyjCount());
                result.setPhyjPersonCount(result.getPhyjPersonCount() + fj.getPhyjPersonCount());
                result.setPhyjHandleCount(result.getPhyjHandleCount() + fj.getPhyjHandleCount());
                ssxq.setPhyjCount(ssxq.getPhyjCount() + fj.getPhyjCount());
                ssxq.setPhyjPersonCount(ssxq.getPhyjPersonCount() + fj.getPhyjPersonCount());
                ssxq.setPhyjHandleCount(ssxq.getPhyjHandleCount() + fj.getPhyjHandleCount());


                result.setRlsbCount(result.getRlsbCount() + fj.getRlsbCount());
                result.setRlsbPersonCount(result.getRlsbPersonCount() + fj.getRlsbPersonCount());
                result.setRlsbHandleCount(result.getRlsbHandleCount() + fj.getRlsbHandleCount());
                ssxq.setRlsbCount(ssxq.getRlsbCount() + fj.getRlsbCount());
                ssxq.setRlsbPersonCount(ssxq.getRlsbPersonCount() + fj.getRlsbPersonCount());
                ssxq.setRlsbHandleCount(ssxq.getRlsbHandleCount() + fj.getRlsbHandleCount());
            }
            qbzxChild.add(ssxq);
        }
        result.setChild(qbzxChild);

    }

    /**
     * 处理给ds推送的预警的手机号码
     *
     * @param data
     */
    private List<ZdryYjPushToDsUtil> handleAssist(List<ZdryYjPushDataVo> data) {
        List<ZdryYjPushToDsUtil> returnData = new ArrayList<>();
        List<SysDictEntity> dicts = iSysDictService.getByType("kp_zrgkfj");
        String ssfjDm = "";
        for (ZdryYjPushDataVo z : data) {
            /* 根据客户要求屏蔽掉以下筛选条件
            // 过滤掉铁路检票的预警
            if (z.getAlarmType().equals("tljp")) {
                continue;
            }
            *//*  data: 20200610
                @清扫战场 杜超，新加一个需求：
                1、给迪爱斯推送中，人员大类“违法犯罪前科”部推送
                2、违法犯罪前科大类中增加两个小类：涉黄、涉赌---字典表更改*//*
            if (z.getType().equals("违法犯罪前科")) {
                continue;
            }*/

            // 同一个人1个小时内，离开区域的直推一次(手机预警，对比时间使用入库时间)
            if (z.getAlarmType().equals("phyj") && z.getAlarmLocation().indexOf("离开区域") >= 0) {
                Integer count = this.getBaseMapper().queryPhyjBySfzh(z.getIdcard());
                if (count > 0) {
                    continue;
                }
            }

            // 预警地分局和派出所
            if (z.getAlarmType().equals("tldp") || z.getAlarmType().equals("mhdz") || z.getAlarmType().equals("mhlg")) {
                z.setPoliceStation("530100160000");//治安支队
            } else {
                //如果9个远郊县  ，推送DS代码直接用分局代码
                if (yjdFjNameMap.keySet().contains(z.getYjdSsfj())) {
                    z.setPoliceStation(yjdFjNameMap.get(z.getYjdSsfj()));
                } else { //如果是9主城区 ，如果派出所为空，则填分分局代码；如果派出所不为空，则填派出所代码 ；
                    for (SysDictEntity dict : dicts) {
                        if (dict.getValue().equals(z.getYjdSsfj())) {
                            ssfjDm = dict.getKey();
                            break;
                        }
                    }
                    String regionPid = "";
                    //判断是否为该分局下的派出所，false 则如下：
                    if (StringUtils.isNotEmpty(z.getPoliceStation())) {
                        regionPid = this.getRegionPid(z.getPoliceStation());
                        //如果派出所对的分局为昆明主城区的9个
                        //如果是9个主城区，如果派出所不属于9个主城区分局，
                        if (StringUtils.isNotEmpty(ssfjDm) && ssfjDm.equals(regionPid)) {
                            z.setPoliceStation(z.getPoliceStation());
                        } else {
                            z.setPoliceStation(ssfjDm);
                        }
                    } else {//如果是9个主城区，如果派出所为空
                        z.setPoliceStation(ssfjDm);
                    }
                }
            }

            List<String> fjList = dicts.stream().map(SysDictEntity::getValue).collect(Collectors.toList());
            // 管控派出所和分局
            if (fjList.size() > 0 && fjList.contains(z.getSsxq())) {//判断管控分局是否在昆明市内
                if (StringUtils.isEmpty(z.getSsxqId())) {
                    for (SysDictEntity dict : dicts) {
                        if (dict.getValue().equals(z.getSsxq())) {
                            z.setSsxqId(dict.getKey());
                            break;
                        }
                    }
                }
                if (ssxqes.contains(z.getSsxqId())) {//9个郊县区
                    z.setControlUnit(z.getSsxqId() == null ? "" : z.getSsxqId());
                } else {//9个主城区
                    if (z.getSsxq().equals("其他单位")) {
                        z.setControlUnit("530100160000");
                    } else {
                        String regionPid = "";
                        //判断是否为该分局下的派出所，false 则如下：
                        if (StringUtils.isNotEmpty(z.getControlUnit())) {
                            regionPid = this.getRegionPid(z.getControlUnit());
                            //如果派出所对的分局为昆明主城区的9个
                            //如果是9个主城区，如果派出所不属于9个主城区分局，
                            if (StringUtils.isNotEmpty(z.getSsxqId()) && z.getSsxqId().equals(regionPid)) {
                                z.setControlUnit(z.getControlUnit());
                            } else {
                                z.setControlUnit(z.getSsxqId());
                            }
                        } else {//如果是9个主城区，如果派出所为空
                            z.setControlUnit(z.getSsxqId());
                        }
                    }
                }
                //昆明的人（管控分局属于昆明），离开昆明辖区（手机预警），预警地赋值管控地代码
                if (z.getAlarmType().equals("phyj") && z.getAlarmLocation().indexOf("离开区域") >= 0) {
                    z.setPoliceStation(z.getControlUnit());
                }
            } else {//管控分局不为昆明
                //手机预警
                //非昆明人员（管控分局为空或者有管控分局但是不属于昆明），离开昆明辖区（手机预警），过滤不推ds
                if (z.getAlarmType().equals("phyj") && z.getAlarmLocation().indexOf("离开区域") >= 0) {
                    continue;
                } else {//其他预警
                    z.setControlUnit("530100160000"); //530100160000 治安支队
                }
            }

            if (z.getAlarmType().equals("tldp") || z.getAlarmType().equals("mhdz") || z.getAlarmType().equals("mhlg") ||
                    z.getAlarmType().equals("glky-gp")) {
                if (null == z.getInOut()) {
                    continue;
                }
            }

            StringBuilder sb = new StringBuilder();
            if (null != z.getAssist() && z.getAssist().size() > 0) {
                //手机号码如果有只取第一个;
                sb.append(z.getAssist().get(0).getInfoValue());
            }
            z.setPhone(sb.toString());
            returnData.add(z.convertToZdryYjPushToDsUtil());
        }
        return returnData;
    }

    public String getRegionPid(String id) {
        ResponseEntity result = restTemplate.getForEntity(
                systemConfig.getSystemServer() + "/api/system/organization/getOrgById?id=" + id,
                JSONObject.class);
        if (null != result) {
            if (null != result.getBody()) {
                JSONObject obj1 = JSONObject.parseObject(result.getBody().toString());
                if (obj1.get("data") != null) {
                    JSONObject data = JSONObject.parseObject(obj1.get("data").toString());
                    String regionPid = data.get("regionPid").toString();
                    return regionPid;
                }
            }
        }
        return null;
    }

    /**
     * 预警查询 权限相关参数
     *
     * @param exchange
     * @param qo
     */
    private void setUpAuthority(ServerWebExchange exchange, LfRyyjsjQO qo) {

        try {
            // 权限相关代码
            AccountBo bo = requestUtils.getCurrentUser(exchange);
            if (bo == null) {
                throw new BusinessException(10019, "此账号已在别处登录，请查证");
            }
            //新增户籍省市县查询
            Map<String, String> regiones = cacheableService.getAllRegionInfo("allRegion");
            List<String[]> hjssxList = new ArrayList<String[]>();
            if (qo.getHjssxList() != null) {
                for (String[] ssxs : qo.getHjssxList()) {
                    String[] ssxChar = new String[3];
                    for (int i = 0; i < ssxs.length; i++) {
                        ssxChar[i] = regiones.get(ssxs[i]);
                    }
                    hjssxList.add(ssxChar);
                }
                qo.setHjssxList(hjssxList);
            }
            String roleType = bo.getRoleList().get(0).getRoleType();
            String orgName = bo.getOrganizationBo().getShortName();
            String orgId = bo.getOrganizationBo().getId();
            /* getOrgName(bo.getOrgId());
             1、管理员、市局情报中心,不加判断条件
             2、市局各警种
             角色类型："管理员", "0")"市局情报中心", "1"), "市局警种", "2"),"分局", "3"),"派出所", "4")
             审批状态：0：待分局审批,1：待警种审核,2：已驳回,3：已完成, 4：上报
             对应的列表参数 zrbmList:警种;  zrfj :分局;  zrmj:民警;  sspcsList:派出所.
             */

            List<OrganizationDto> organizationDtos = cacheableService.getUpOrgById(bo.getOrganizationBo().getId());

            if (roleType.equals(RoleType.OWNER_ADMIN_ORG_DATA.getType())) { // 1:市局情报中心

            } else if (roleType.equals(RoleType.OWNER_REVIEW_DATA.getType())
                    || roleType.equals(RoleType.OWNER_ORG_DATA.getType())) { // 5:市局警种和2:市局警种审核
                if (null == qo.getZrbmList() || qo.getZrbmList().size() == 0) {
                    OrganizationDto org = getOrganizationByCondition(organizationDtos, "支队");
                    qo.setZrbmList(Arrays.asList(org.getShortName()));
                }
            } else if (roleType.equals(RoleType.BREACH_REVIEW_DATA.getType())
                    || roleType.equals(RoleType.BREACH_DATA.getType())) { // 6:分局 和 3:分局审核
                if (null == qo.getZrfj() || qo.getZrfj().size() == 0) {
                    OrganizationDto org1 = getOrganizationByCondition(organizationDtos, "分局");
                    if (null != org1) qo.setZrfj(Arrays.asList(org1.getId()));
                    OrganizationDto org2 = getOrganizationByCondition(organizationDtos, "县局");
                    if (null != org2) qo.setZrfj(Arrays.asList(org2.getId()));
                    OrganizationDto org3 = getOrganizationByCondition(organizationDtos, "市局");
                    if (null != org3) qo.setZrfj(Arrays.asList(org3.getId()));
                }
            } else if (roleType.equals(RoleType.POLICE_STATION_DATA.getType())) { // 派出所4
                if (null == qo.getSspcsList() || qo.getSspcsList().size() == 0) {
                    OrganizationDto org = getOrganizationByCondition(organizationDtos, "派出所");
                    if (null != org) qo.setSspcsList(Arrays.asList(org.getId()));
                }
            }

        } catch (BusinessException e) {
            log.error("权限参数异常或者筛选参数异常：======>{}", e.getMessage());
            if ("此账号已在别处登录，请查证".equals(e.getMessage())) {
                throw new BusinessException(10019, "此账号已在别处登录，请查证");
            }
        }
    }

    /**
     * 根据条件查询对应单位
     *
     * @param organizationDtos
     * @param con
     * @return
     */
    private OrganizationDto getOrganizationByCondition(List<OrganizationDto> organizationDtos, String con) {
        OrganizationDto result = null;
        for (OrganizationDto org : organizationDtos) {
            if (org.getShortName().indexOf(con) >= 0) {
                result = org;
                break;
            }
        }
        return result;
    }
}
